// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const pluginName = 'slackoff'
const vscode = require('vscode');
const path = require('path');
// 扩展被激活时，会调用此方法
// 扩展在第一次执行命令时被激活

/**
 * @param {vscode.ExtensionContext} context
 */ 
function activate(context) {
	const app = new App(context)
	app.init()
	console.log('拓展激活');
		
	// Use the console to output diagnostic information (console.log) and errors (console.error)
	// This line of code will only be executed once when your extension is activated

	// The command has been defined in the package.json file
	// Now provide the implementation of the command with  registerCommand
	// The commandId parameter must match the command field in package.json
	const disposable = vscode.commands.registerCommand('test.helloWorld', function () {
		// The code you place here will be executed every time your command is executed
		// Display a message box to the user
		vscode.window.showInformationMessage('Hello World from test!');
	});
	context.subscriptions.push(disposable);
}

// 扩展被停用时回调
function deactivate() {
	console.log('拓展结束');
}




/**
 * @param {vscode.ExtensionContext} ctx
 */ 
class App {
	constructor(ctx) {
		this.ctx = ctx
		this.tabBar = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right)
	}
	init() {
		this.addCommands()
		this.addEffBar()
		// this.addIcon()
		console.log('初始化完成');
	}
	// 添加命令
	addCommands() {
		const disposable = vscode.commands.registerCommand(`slackoff.stateBarBrowser`, async () => {
			const tabName = 'Index.js'
			const webViewConf = {
				enableScripts: !0,
				enableCommandUris: !0,
				retainContextWhenHidden: !0,
				enableFindWidget: !0,
				localResourceRoots: [vscode.Uri.file(this.ctx.extensionPath)],
			}
			// 窗口放到第一个browser
			const browserTab = vscode.window.createWebviewPanel('catCoding', tabName, vscode.ViewColumn.One, {
				enableScripts: true,	// 允许脚本执行
				retainContextWhenHidden: true // 隐藏时保持上下文（切换tab时不重新加载）
			})
			const filePath = path.join(__dirname, '/src/index.html')
			const content = await this.readFileContent(filePath);
			// const scriptPath = vscode.Uri.joinPath(this.ctx.extensionUri, 'src/index.js');
      // const scriptUri = browserTab.webview.asWebviewUri(scriptPath);
			const jsfilePath = path.join(__dirname, '/src/index.js')
			const jscontent = await this.readFileContent(jsfilePath);
			browserTab.webview.html = content.replace('${scriptUri}', jscontent)
			//content.replace('${scriptUri}', scriptUri)
			// 注册事件监听
			browserTab.webview.onDidReceiveMessage((msg) => {
				switch(msg.command) {
				}
			}, null, this.ctx.subscriptions)

		});
		this.ctx.subscriptions.push(disposable);
	}
	// 添加右下角功能入口
	addEffBar() {
		this.tabBar.text = '🦀Rust'
		this.tabBar.command = `slackoff.stateBarBrowser`
		this.tabBar.show()
	}
	addIcon() {
		vscode.window.registerWebviewViewProvider('Index.js', {
			resolveWebviewView: (webviewViewcontext, token) => {
				webviewViewcontext.webview.options = {
							enableScripts: true,
					};

					webviewViewcontext.webview.html = `
							<!DOCTYPE html>
							<html lang="en">
							<head>
									<meta charset="UTF-8">
									<meta name="viewport" content="width=device-width, initial-scale=1.0">
									<title>My View</title>
							</head>
							<body>
									<h1>This is a custom view</h1>
							</body>
							</html>
					`;

					return webviewViewcontext;
			},
	}, {
			webviewOptions: {
					enableFindWidget: true,
			},
			iconPath: vscode.Uri.file(this.ctx.asAbsolutePath('/icon.jpg')) // Set your icon path here
	});
	}
	readFileContent(filePath) {
    const uri = vscode.Uri.file(filePath);
    return vscode.workspace.fs.readFile(uri).then(data => {
        return new TextDecoder().decode(data);
    }).catch(error => {
        console.error(`Error reading file: ${error.message}`);
        return null;
    });
}
}

module.exports = {
	activate,
	deactivate
}
